package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * Title  : 173. Binary Search Tree Iterator
 * Source : https://leetcode.cn/problems/binary-search-tree-iterator/description/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-09-14
 */

public class LeetCode_173 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class BSTIterator {
        private List<Integer> iterator;
        private int index;

        //扁平化处理
        public BSTIterator(TreeNode root) {
            iterator = new ArrayList<>();
            index = 0;
            ArrayDeque<TreeNode> sta = new ArrayDeque<>();
            TreeNode p = root;
            while (p != null || !sta.isEmpty()) {
                while (p != null) {
                    sta.push(p);
                    p = p.left;
                }
                TreeNode node = sta.pop();
                iterator.add(node.val);
                p = node.right;
            }
        }

        public int next() {
            return iterator.get(index++);
        }

        public boolean hasNext() {
            return index < iterator.size();
        }
    }
}
